<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:56
 */

namespace app\home\controller;

use app\admin\model\InvitationRebateRecord;
use app\admin\model\Invitation;
use app\home\model\Member;
use think\Cookie;
use think\Loader;
use think\Db;
use think\Log;
use app\admin\model\Config;
use app\home\model\CreditRecord;

class Auth extends  Base{

    //登录
    public function login(){
        if($this->request->isAjax()){
            $params = array_trim(request()->post());
            //$validate = $this->validate($params,'Member.login');
            if(empty($params['username']) || empty($params['password'])){
                message('账号密码错误','','error');
            }
            /*if($validate !== true){
                message($validate,'','error');
            }*/
            $member = Member::getUserInfoByUsername($params['username']);
            if(empty($member) || $member['is_del'] == 1){
                message('会员信息不存在','','error');
            }
            if(!md5_password_check($params['password'],$member['password'],$member['salt'])){
                message('密码输入错误','','error');
            }
            if($member['is_check'] == 0){
            	
                if($member['frozen_time']){
                    $frozen_time=strtotime($member['frozen_time']);
                    if(time()>$frozen_time){
                        //更新状态
                        $frozen_data=[
                            'uid'=>$member['uid'],
                            'is_check'=>1,
                            'frozen_reason'=>'',
                            'frozen_time'=>'',

                        ];
                        db('member')->update($frozen_data);
                    }else{
                    	$member['frozen_reason']=$member['frozen_reason']?:'违反用户协议';
                    	$member['frozen_time']=$member['frozen_time']?:'无';
                        message('由于' . $member['frozen_reason'] . ',您已被管理员禁止登录,解封时间'.$member['frozen_time'],'','error');
                    }
                }else{
                	$member['frozen_reason']=$member['frozen_reason']?:'违反用户协议';
                    	$member['frozen_time']=$member['frozen_time']?:'无';
                        message('由于' . $member['frozen_reason'] . ',您已被管理员禁止登录,解封时间'.$member['frozen_time'],'','error');
                }
         
               
            }
            $ip=getIp();
            db('member')->where('uid',$member['uid'])->setField('ip',$ip);
            
            Cookie::set('member',base64_encode($member));
            message('登录成功','/home/account.html','success');
        }
        Cookie::delete('member');
        return $this->fetch(__FUNCTION__);
    }
    
        //登录
    public function login2(){
        if($this->request->isAjax()){
            $params = array_trim(request()->post());
            //$validate = $this->validate($params,'Member.login');
            if(empty($params['username']) || empty($params['password'])){
                message('账号密码错误','','error');
            }
            /*if($validate !== true){
                message($validate,'','error');
            }*/
            $member = Member::getUserInfoByUsername($params['username']);
            if(empty($member) || $member['is_del'] == 1){
                message('会员信息不存在','','error');
            }
            if(!md5_password_check($params['password'],$member['password'],$member['salt'])){
                message('密码输入错误','','error');
            }
            if($member['is_check'] == 0){
            	
                if($member['frozen_time']){
                    $frozen_time=strtotime($member['frozen_time']);
                    if(time()>$frozen_time){
                        //更新状态
                        $frozen_data=[
                            'uid'=>$member['uid'],
                            'is_check'=>1,
                            'frozen_reason'=>'',
                            'frozen_time'=>'',

                        ];
                        db('member')->update($frozen_data);
                    }else{
                    	$member['frozen_reason']=$member['frozen_reason']?:'违反用户协议';
                    	$member['frozen_time']=$member['frozen_time']?:'无';
                        message('由于' . $member['frozen_reason'] . ',您已被管理员禁止登录,解封时间'.$member['frozen_time'],'','error');
                    }
                }else{
                	$member['frozen_reason']=$member['frozen_reason']?:'违反用户协议';
                    	$member['frozen_time']=$member['frozen_time']?:'无';
                        message('由于' . $member['frozen_reason'] . ',您已被管理员禁止登录,解封时间'.$member['frozen_time'],'','error');
                }
         
               
            }
            $ip=getIp();
            db('member')->where('uid',$member['uid'])->setField('ip',$ip);
            Cookie::set('member',base64_encode($member));
            message('登录成功','/home/account.html','success');
        }
        Cookie::delete('member');
        return $this->fetch(__FUNCTION__);
    }
    
        public function wxLogin(){
         if($this->request->isAjax()){
            $params=request()->param();
            if(empty($params['openid'])){
                message('登录错误','reload','error');
            }
            $member=db('member')->where('openid2',$params['openid'])->find();
            if(!$member || $member['is_del']){
                message('请登录后绑定微信','','error');
            }

            if($member['is_check'] == 0){
                if($member['frozen_time']){
                    $frozen_time=strtotime($member['frozen_time']);
                    if(time()>$frozen_time){
                        //更新状态
                        $frozen_data=[
                            'uid'=>$member['uid'],
                            'is_check'=>1,
                            'frozen_reason'=>'',
                            'frozen_time'=>'',
                        ];
                        db('member')->update($frozen_data);
                    }else{
                        $member['frozen_reason']=$member['frozen_reason']?:'违反用户协议';
                        $member['frozen_time']=$member['frozen_time']?:'无';
                        message('由于' . $member['frozen_reason'] . ',您已被管理员禁止登录,解封时间'.$member['frozen_time'],'','error');
                    }
                }else{
                    $member['frozen_reason']=$member['frozen_reason']?:'违反用户协议';
                        $member['frozen_time']=$member['frozen_time']?:'无';
                        message('由于' . $member['frozen_reason'] . ',您已被管理员禁止登录,解封时间'.$member['frozen_time'],'','error');
                }
            }
            
            $update_data=[
            		'avatar'=>request()->param('headimgurl'),
            		'nickname'=>request()->param('nickname'),
            		'uid'=>$member['uid'],
        	];
            //	db('member')->update($update_data);
            $ip=getIp();
            db('member')->where('uid',$member['uid'])->setField('ip',$ip);
            Cookie::set('member',base64_encode(json_encode($member)));
            message('登录成功','/home/account.html','success');
         }
    }
    
    
    public function bind_login(){
        
        //Cookie::delete('member');
        return $this->fetch(__FUNCTION__);
    }
    public function bind_ac(){

            $params = array_trim(request()->get());
            if(empty($params['username']) || empty($params['password'])){
                
                echo "账号密码不能为空";die;
            }
            $member = Member::getUserInfoByUsername($params['username']);
            if(empty($member) || $member['is_del'] == 1){
               
                echo "会员信息不存在";die;
            }
            if(!md5_password_check($params['password'],$member['password'],$member['salt'])){
                
                echo "密码输入错误";die;
            }
            if($member['is_check'] == 0){
               
                echo "已被管理员禁止登录";die;
            }
            Cookie::set('member',base64_encode($member));
          // header('Location: http://jfcms12.com/openid1.php?mid=3015&url=http://'.$_SERVER['SERVER_NAME'].'/home/account/bind_wx.html?u=1');
           header('Location:http://api.zs006.cn/api/api/getOpenid?redirect_uri=http://'.$_SERVER['SERVER_NAME'].'/home/account/bind_wx.html?u=1');

        
    }
    //判断是否微信内部打开
    public function is_weixin(){ 
        if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false){
            return true;
        }else{
            return false; 
        }       
    }
  
    public function linkreg(){
   
    $member =  trim(params('member'))? trim(params('member')):0;
     return $this->fetch(__FUNCTION__,['member'=>$member]);
  }
  
   public function registe()
    {
        $mobile = trim(params('txtaccount'));
        $code =  trim(params('txtcode'));
        $pass = trim(params('txtpwd'));
        $member = trim(params('member'));
        if($code != session('smscode')){
            $this->error('短信验证码错误!');
        }
        //请求地址
        header('Location: http://koqawi.cn/home/auth/linkregis.html?mobile='.$mobile.'&pass='.$pass.'&member='.$member);
    }
  
    public function userprotocol(){
        return $this->fetch(__FUNCTION__);
    }

    public function linkregis()
    {
    
        $params['username'] = input('mobile');
        $params['password'] = input('pass');
        if($params['username']==''){
            $json_data['code'] =0;
            $json_data['msg'] ='请输入手机号';
            echo json_encode($json_data);die;
        }
     
        $parent_uid = trim(input('member'));
        if ($parent_uid > 0) {
            $parent_member = Member::getUserInfoById($parent_uid);
        }
      	$username = Member::getUserInfoByUsername($params['username']);
      	if($username){
        	//$this->error('手机号已被注册');
            $json_data['code'] =0;
            $json_data['msg'] ='手机号已被注册';
            echo json_encode($json_data);die;
        }
        Db::startTrans();
        $params['parent_uid'] = $parent_uid;
        $params['salt'] = random(8);
        $params['password'] = md5_password($params['password'],$params['salt']);
        $params['create_time'] = TIMESTAMP;
        $params['pet_jihua'] = date('Ymd');
        $params['ip']=input('ip');
        unset($params['password_confirm'],$params['invitation_code'],$params['captcha']);
        
        $insert_member_id = Member::addInfo($params);

        if ($parent_uid > 0) {
            $status3 = Invitation::addInfo([
                'uid' => $parent_member['uid'],
                'username' => $parent_member['username'],
                'invite_uid' => $insert_member_id,
                'invite_username' => $params['username'],
                'create_time' => TIMESTAMP
            ]);
            if(!$status3){
                Db::rollback();
                
                 $json_data['code'] =0;
	            $json_data['msg'] ='上级信息错误';
	            echo json_encode($json_data);die;
            
            }

            $status4 = Member::updateInviteInfo($parent_uid);
            if(!$status4){
                Db::rollback();
                
                $json_data['code'] =0;
	            $json_data['msg'] ='更新用户信息错误';
	            echo json_encode($json_data);die;
	            
            }
        }

        Db::commit();

        //$this->success("注册成功",'home/auth/login');
        $json_data['code'] =200;
        $json_data['msg'] ='注册成功';
        echo json_encode($json_data);die;

    }

    //注册
    public function register(){
        
        $code = trim(params('i'));
        $parent_uid = "";
        if(!empty($code)){
            $tempMember = Member::getUserInfoByCode($code);
            if(!empty($tempMember)){
                $parent_uid = $tempMember['uid'];
            } 
        }
        //$parent_uid = intval(trim(params('i')));

        if(request()->isAjax()){
            $params = array_trim(request()->post());
            if(empty($params['username']) || empty($params['password_confirm']) || empty($params['password']) || $params['password'] != $params['password_confirm']){
            	
                   message("手机号密码不能为空！
                   ",'','error'); 
            }
//           if(empty($params['nickname']))
//           {
//              message("用户昵称不能为空",'','error');
//           }
//          else
//          {
//             $nicknum=Db::name("member")->where('nickname',$params['nickname'])->count();
//            if($nicknum>0)
//            {
//              message("用户昵称已被注册",'','error');
//            }
//          }
          
            if($params['captcha'] != session('smscode')){
                message("验证码错误",'','error');
            }
            if($params['username'] != session('yourmobile')){
                message("手机号必须与接收验证码端一致",'','error');
            }
            

            /*$validate = Loader::validate('Member');
            if(!$validate->check($params)){
                message($validate->getError(),'','error');
            }*/

            $parent_member = [];
            if(!empty($params['yaoqingma'])){
               $tempMember = Member::getUserInfoByCode($params['yaoqingma']);
                if(!empty($tempMember)){
                    $parent_uid = $tempMember['uid'];
                    $parent_member = $tempMember;
                } else {
                    message('邀请失败','','error');
                }
            }
            
          	$username = Member::getUserInfoByUsername($params['username']);
          	if($username){
            	message('手机号已被注册','','error');
            }

            #Db::startTrans();
            $params['parent_uid'] = $parent_uid;
          	$params['ip']=getIp();
            $params['salt'] = random(8);
            $params['invitation_code'] = random(6);
            $params['password'] = md5_password($params['password'],$params['salt']);
            $params['create_time'] = TIMESTAMP;
            $params['pet_jihua'] = date('Ymd');
            $params['nickname'] = $params['username'];
            
            unset($params['password_confirm'],$params['yaoqingma'],$params['captcha']);
            
            $insert_member_id = Member::addInfo($params);
            if(!$insert_member_id){
                message('注册失败1','','error');
            }

            if ($parent_uid > 0) {
                $status3 = Invitation::addInfo([
                    'uid' => $parent_member['uid'],
                    'username' => $parent_member['username'],
                    'invite_uid' => $insert_member_id,
                    'invite_username' => $params['username'],
                    'create_time' => TIMESTAMP
                ]);
                if(!$status3){
                    Db::rollback();
                    message('注册失败','','error');
                }

                $status4 = Member::updateInviteInfo($parent_uid);
                if(!$status4){
                    Db::rollback();
                    message('注册失败','','error');
                }
            }

            Db::commit();

            message('注册成功','/home/auth/login.html','success');
        }
        return $this->fetch(__FUNCTION__, [
            'parent_uid' => $parent_uid,
            'code' => (empty($code)?'':$code)
        ]);
    }

        public function findpwd(){
        if(request()->isAjax()){
            $params = array_trim(request()->post());
            if(empty($params['username']) || empty($params['password_confirm']) || empty($params['password']) || $params['password'] != $params['password_confirm']){
                message("手机号密码错误",'','error');
            }
            if($params['captcha'] != session('smscode')){
                message("验证码错误",'','error');
            }
            $username = Member::getUserInfoByUsername($params['username']);
            if(!$username){
                message('手机号不存在','','error');
            }
            $map['salt'] = random(8);
            $map['password'] = md5_password($params['password'],$map['salt']);
            $res = Db::name("member")->where('username',$params['username'])->update($map);
            if($res){
                message('修改密码成功','/home/auth/login.html','success');
            }
            message('修改失败','','error');
        }
        return $this->fetch(__FUNCTION__);
    }
    public function zrb_reward(){
        $uid = $_GET['uid'];
        $points = $_GET['points'];
        $orderid = $_GET['orderid'];
        //ordername -- 玩家参与任务的任务名称
        $ordername = $_GET['ordername'];
        //token  --  密码验证
        $token = $_GET['token'];
        //密钥，添加任务墙时，生成的密钥
        $appkey = "oiy5tkyacidecid9";
        $rs_json = array('uid'=>$uid,'points'=>$points,'orderid'=>$orderid);
        if(empty($uid) || empty($points) || empty($orderid)|| empty($ordername)|| empty($token)){
            $this->write_hd_log(':缺少某些回调参数'.json_encode($_GET));
        }
        $pwd = $uid.$points.$orderid.$appkey;

        //判断密码是否匹配
        if(md5($pwd) == $token){
            //检测玩家id(uid)是否存在
            $userinfo = db('member')->where('uid',$uid)->find();
            if(!$userinfo){
                $this->write_hd_log(':用户不存在');
            }  
            $config = Config::getInfo();
            //给用户充值并记录到数据库中
            //区分用户是否vip给与不同的积分奖励
            // if($userinfo['level']>1){
            //     //大于1的为vip
            //     $jifen = $points*$config['setting']['zengjifen'];
            // }else{
            //     $jifen = $points; 
            // }
            $jifen = $points;
            $credit['over_task_num'] = $userinfo['over_task_num']+1;
            $credit['credit2'] = $userinfo['credit2']+$jifen;
            $credit['pet_need_credit'] = $userinfo['pet_need_credit']+$jifen;
            
            //记录每日
        $you_userinfo = db('member')->where('uid',$uid)->find();
        if($you_userinfo['partition_status']==1){
            $jackpot = db('jackpot')->where('uid',$uid)->where('today_time',date('Ymd'))->find();
            if($jackpot['num']>$you_userinfo['partition_num']){
                
                $credit['partition_num'] = $you_userinfo['partition_num']+1;
                if($jackpot['num']==$you_userinfo['partition_num']+1){
                	$credit['partition_status']=2;
                }
            }
        }
        db('member')->where('uid',$uid)->update($credit);
        CreditRecord::addInfo([
                        'uid' => $uid,
                        'type' => 'credit2',
                        'num' => $jifen,
                        'title' => '完成任务奖励',
                        'remark' => "领取成功，奖励".$jifen."。",
                        'create_time' => TIMESTAMP
                    ]);
       
		$setting = [
		    'invitation_one_rebate' => 0,
		    'invitation_two_rebate' => 0,
		    'invitation_three_rebate' => 0,
		    'invitation_vip_one_rebate' =>0,
		    'invitation_vip_two_rebate' =>0,
		    'invitation_vip_three_rebate' =>0,
		    'kc_money' =>0
		    ];
        $config = Config::getInfo();

        if(check_array($config['setting'])){
            $setting = $config['setting'];
            if(!empty($setting['invitation_one_rebate'])){
                $setting['invitation_one_rebate'] = round(floatval($setting['invitation_one_rebate']/100),2);
            }
            if(!empty($setting['invitation_two_rebate'])){
                $setting['invitation_two_rebate'] = round(floatval($setting['invitation_two_rebate']/100),2);
            }
            if(!empty($setting['invitation_three_rebate'])){
                $setting['invitation_three_rebate'] = round(floatval($setting['invitation_three_rebate']/100),2);
            }
            if(!empty($setting['invitation_vip_one_rebate'])){
                $setting['invitation_vip_one_rebate'] = round(floatval($setting['invitation_vip_one_rebate']/100),2);
            }
            if(!empty($setting['invitation_vip_two_rebate'])){
                $setting['invitation_vip_two_rebate'] = round(floatval($setting['invitation_vip_two_rebate']/100),2);
            }
            if(!empty($setting['invitation_vip_three_rebate'])){
                $setting['invitation_vip_three_rebate'] = round(floatval($setting['invitation_vip_three_rebate']/100),2);
            }	 
            if(!empty($setting['kc_money'])){
                $setting['kc_money'] = round(floatval($setting['kc_money']/100),2);
            }	            
        }             
        
        	$unit_price=$jifen;
	        $parent_money = round($unit_price * $setting['invitation_one_rebate'], 2);
	        $parent = \db('member')->where(['uid'=>$you_userinfo['parent_uid']])->find();        
            
            if ($parent && $parent_money > 0 ) {
            	
                if($parent['level'] > 1){
                    $parent_money = round($unit_price * $setting['invitation_vip_one_rebate'], 2);
                }
            	
            
                $status1 = Member::updateCreditById($parent['uid'], 0, $parent_money);

				if($status1){
					$status3 = CreditRecord::addInfo([
	                    'uid' => $parent['uid'],
	                    'type' => 'credit2',
	                    'num' => $parent_money,
	                    'title' => '审核任务',
	                    'remark' => "一级[" . $you_userinfo['uid'] . "]完成任务，获得推荐收入{$parent_money}元。",
	                    'create_time' => TIMESTAMP
	                ]);
	           
	                InvitationRebateRecord::addInfo([
	                            'uid' => $parent['uid'],
	                            'num' => $parent_money,
	                            'task_id' => 11,
	                            'tuijian_id' =>$you_userinfo['uid'],
	                            'remark' => "一级[" . $you_userinfo['uid'] . "]完成任务，获得推荐收入{$parent_money}元.。",
	                            'create_time' => TIMESTAMP
	                        ]);
  
	
	                        
					//给上上级的奖励
					//是否存在上上级
					$grand_info=db('member')->find($parent['parent_uid']);
					$grand_money= round($unit_price * $setting['invitation_two_rebate'], 2);
					
					if($grand_info && $grand_money>0){
                            if($grand_info['level'] > 1){
                                $grand_money = round($unit_price * $setting['invitation_vip_two_rebate'], 2);
                            }					    
					    
							 Member::updateCreditById($grand_info['uid'], 0, $grand_money);
							  
							   $statusp = CreditRecord::addInfo([
			                    'uid' => $grand_info['uid'],
			                    'type' => 'credit2',
			                    'num' => $grand_money,
			                    'title' => '审核任务',
			                    'remark' => "二级[" . $you_userinfo['uid'] . "]完成任务，获得推荐收入{$grand_money}元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
				                
			                InvitationRebateRecord::addInfo([
			                            'uid' => $grand_info['uid'],
			                            'num' => $grand_money,
			                            'task_id' => 0,
			                            'tuijian_id' =>$you_userinfo['uid'],
			                            'remark' => "二级[" . $you_userinfo['uid'] . "]完成任务，获得推荐收入{$grand_money}元.。",
			                            'create_time' => TIMESTAMP
			                        ]);
			                        
			                        
						
					}
					
                //新增三级
					$parent3=db('member')->find($grand_info['parent_uid']);
					$parent3_money= round($unit_price * $setting['invitation_three_rebate'], 2);
					
					if($parent3 && $parent3_money>0){
                            if($parent3['level'] > 1){
                                $parent3_money = round($unit_price * $setting['invitation_vip_three_rebate'], 2);
                            }					    
					    
							 Member::updateCreditById($parent3['uid'], 0, $parent3_money);
							  
							   $statusp = CreditRecord::addInfo([
			                    'uid' => $parent3['uid'],
			                    'type' => 'credit2',
			                    'num' => $parent3_money,
			                    'title' => '审核任务',
			                    'remark' => "三级[" . $you_userinfo['uid'] . "]完成任务，获得推荐收入{$parent3_money}元。",
			                    'create_time' => TIMESTAMP
			                ]);
			                
				                
			                InvitationRebateRecord::addInfo([
			                            'uid' => $parent3['uid'],
			                            'num' => $parent3_money,
			                            'task_id' => 0,
			                            'tuijian_id' =>$you_userinfo['uid'],
			                            'remark' => "三级[" . $you_userinfo['uid'] . "]完成任务，获得推荐收入{$parent3_money}元.。",
			                            'create_time' => TIMESTAMP
			                        ]);
			                        
			                        
						
					}
					
				}
				
                
                


			//	$status4 = Member::updateInviteInfo($joinMemberInfo['parent_uid'], 0, $parent_money);


          
            }            
            
                        
           // $joinMemberInfo = Member::getUserInfoById($uid);            
            //task_reward($joinMemberInfo,$params);            
        }else{
            $this->write_hd_log(':校验失败');
        }
    }
    public function write_hd_log($msg){
        $fp = fopen('./logs/'.date('Ymd').'ddd.log',"a");
        fwrite($fp,date('Y-m-d H:i:s').$msg."\r\n");
        fclose($fp);die;
    }
}